<template>
  <div class="main-box">
    <div class="table-box">
      <ProTable ref="proTable" :columns="columns" :request-api="getDepartmentListApi" :row-key="'FId'" :init-param="initParam">
        <!-- 表头按钮 -->
        <template #tableHeader>
          <el-button v-auth="'department:add'" type="primary" :icon="CirclePlus" @click="openDialog()">新增部门</el-button>
        </template>

        <!-- 部门名称列 -->
        <template #name="{ row }">
          <span>{{ row.FName }}</span>
          <el-tag v-if="!row.FParentId" type="success" size="small" style="margin-left: 8px">顶级部门</el-tag>
        </template>

        <!-- 操作列 -->
        <template #operation="{ row }">
          <el-button v-auth="'department:edit'" type="primary" link :icon="EditPen" @click="openDialog(row)">编辑</el-button>
          <el-button v-auth="'department:delete'" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </ProTable>
    </div>

    <!-- 部门编辑弹窗 -->
    <DepartmentDialog v-if="showDialog" ref="DepartmentDialogRef" @refresh="refreshTable" @close="closeDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import DepartmentDialog from "./components/DepartmentDialog.vue";
import { getDepartmentListApi, deleteDepartmentApi } from "@/api/modules/department";
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";

// 表格和弹窗引用
const proTable = ref<ProTableInstance>();
const DepartmentDialogRef = ref<InstanceType<typeof DepartmentDialog>>();

// 控制弹窗显示
const showDialog = ref(false);

const initParam = reactive({});

const columns: ColumnProps[] = [
  { prop: "FId", label: "部门ID", width: 100 },
  { prop: "FName", label: "部门名称", width: 200 },
  { prop: "FCreatedAt", label: "创建时间", width: 180 },
  { prop: "FUpdatedAt", label: "更新时间", width: 180 },
  { prop: "operation", label: "操作", fixed: "right", width: 180 }
];

// 刷新表格
const refreshTable = () => {
  proTable.value?.getTableList();
};

// 打开新增/编辑弹窗
const openDialog = (row?: any) => {
  showDialog.value = true;
  nextTick(() => {
    DepartmentDialogRef.value?.open(row);
  });
};

// 关闭弹窗
const closeDialog = () => {
  showDialog.value = false;
};

// 删除部门
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确认删除部门 "${row.FName}"?`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });

    await deleteDepartmentApi({ FId: row.FId });
    ElMessage.success("删除成功");
    refreshTable();
  } catch {
    // 用户取消
  }
};
</script>

<style scoped>
.main-box {
  display: flex;
  height: 100%;
  .table-box {
    flex: 1;
    margin-left: 20px;
    overflow: hidden;
  }
}
</style>
